<template>
  <div>
    <!-- 头部 -->
    <div class="search">
      <el-row :gutter="20">
        <el-col :span="2">
          <el-tooltip class="item" effect="dark" content="批量删除" placement="bottom">
            <el-button @click="handleDeleteBatchTips" type="danger" icon="el-icon-delete"></el-button>
          </el-tooltip>
        </el-col>
        <el-col :span="4">
          <el-input @keyup.native.enter="search" placeholder="请输入教室名" v-model="key" clearable></el-input>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button @click="search" type="primary" icon="el-icon-search" circle></el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 表格内容 -->
    <div>
      <el-card>
        <el-table
          v-show="isShowTable"
          @selection-change="handleSelectionChange"
          tooltip-effect="dark"
          stripe
          border
          height="480"
          :data="applyDataList"
          style="width: 100%"
        >
          <el-table-column type="selection" width="40"></el-table-column>
          <el-table-column label="编号" prop="applyId" width="200px"></el-table-column>
          <el-table-column align="center" sortable prop="classroomName" label="教室名" width="120"></el-table-column>
          <el-table-column
            :filters="[{ text: '审核中', value: 0 }, { text: '审核通过', value: 1 },{text: '已驳回', value: 2 }]"
            :filter-method="filterTag"
            filter-placement="bottom-end"
            align="center"
            sortable
            prop="applyStatus"
            label="申请进度"
            width="120"
          >
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>审核人: {{ scope.row.reviewer }}</p>
                <p>审核时间: {{ scope.row.reviewerTime }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag type="primary" v-show="scope.row.applyStatus==0" effect="dark">待审核</el-tag>
                  <el-tag type="success" v-show="scope.row.applyStatus==1" effect="dark">审核通过</el-tag>
                  <el-tag type="warning" v-show="scope.row.applyStatus==2" effect="dark">已驳回</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>

          <el-table-column sortable prop="beginTime" label="使用开始时间 " width="150"></el-table-column>
          <el-table-column sortable prop="endTime" label="使用结束时间" width="150"></el-table-column>
          <el-table-column align="center" sortable prop="interval" label="时长" width="120">
            <template slot-scope="scope">
              <el-tag type="info">{{scope.row.interval}} 分钟</el-tag>
            </template>
          </el-table-column>

          <el-table-column align="center" prop label="申请人姓名" width="120">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>个人邮箱: {{ scope.row.applicantEmail }}</p>
                <br />申请原因：
                <p v-html="scope.row.usedReason"></p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.applicant }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column align="center" sortable prop="gmtCreate" label="提交时间" width="150"></el-table-column>
          <el-table-column label="操作" fixed="right" width="177px">
            <template slot-scope="scope">
              <el-dialog :modal="false" title="温馨提示" :visible.sync="isShowDeleteDialog" width="20%">
                <span>确定要删除吗？</span>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="isShowDeleteDialog = false">点错了</el-button>
                  <el-button type="primary" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </span>
              </el-dialog>

              <el-button size="mini" type="warning" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="isShowDeleteDialog = true ">删除申请</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 编辑对话框 -->

    <el-dialog
      :before-close="handleClose"
      width="50%"
      title="修改预定信息"
      :visible.sync="dialogFormVisible"
    >
      <el-form :rules="rulesApply" ref="applyRef" label-position="left" :model="applyData">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label-width="100px" label="预定编号:">
              <el-tag v-text="applyData.applyId" type="primary" effect="dark">1556515615</el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="100px" label="申请人：">
              <el-tag v-text="applyData.applicant" type="info" effect="dark">1556515615</el-tag>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="100px" prop="reviewer" label="审核人:">
              <el-tag v-text="applyData.reviewer" type="info" effect="dark">1556515615</el-tag>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="100px" prop="classroomName" label="教室：">
              <el-select
                clearable
                filterable
                @focus="changeClassroom"
                v-model="applyData.classroomName"
                placeholder="请选择教室"
              >
                <el-option
                  v-for="item in classroomOptions"
                  :key="item.classroomId"
                  :label="item.classroomName"
                  :value="item.classroomName"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="100px" prop="beginTime" label="开始时间：">
              <el-date-picker
                placeholder="选择开始时间:"
                prefix-icon="el-icon-time"
                type="datetime"
                v-model="applyData.beginTime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                @blur="checkIsConflict"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label-width="100px" prop="endTime" label="结束时间：">
              <el-date-picker
                prefix-icon="el-icon-time"
                type="datetime"
                placeholder="结束时间:"
                v-model="applyData.endTime"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm"
                @blur="checkIsConflict"
              ></el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label-width="100px" prop="usedReason" label="申请理由：">
              <div class="edit_container">
                <quill-editor
                  v-model="applyData.usedReason"
                  ref="myQuillEditor"
                  :options="editorOption"
                ></quill-editor>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button
          type="primary"
          :disabled="isDisableSubmitButton"
          @click="onSubmitApply('applyRef')"
        >确 定</el-button>
      </div>
    </el-dialog>

    <!-- 批量删除对话框 -->
    <el-dialog title="温馨提示" :visible.sync="deleteBatchDialog" width="30%">
      <span>确定要删除当前选中的吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteBatchDialog = false">取 消</el-button>
        <el-button type="primary" @click="batchDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ApplyHistory",
  inject: ["reload"],
  data() {
    return {
      applyDataList: [
        {
          applyId: "",
          applicant: "",
          applicantEmail: "",
          classroomName: "",
          beginTime: "",
          endTime: "",
          interval: "",
          usedReason: "",
          applyStatus: 0,
          reviewer: ""
        }
      ],
      reviewerList: {},
      classroomList: {},
      applyData: {},
      currentPage: 1,
      size: 10,
      total: 0,
      key: "",
      applyIdList: [],
      dialogFormVisible: false,
      classroomOptions: [],
      isDisableSubmitButton: false,
      rulesApply: {
        usedReason: [
          { required: true, message: "申请理由不能为空", trigger: "blur" },
          { min: 5, message: "至少5个字符", trigger: "blur" }
        ],
        beginTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ],
        classroomName: [
          { required: true, message: "教室不能为空", trigger: "blur" }
        ],
        reviewer: [
          { required: true, message: "审核人不能为空", trigger: "blur" }
        ]
      },
      isShowDeleteDialog: false,
      deleteBatchDialog: false,
      isShowTable: false,
      editorOption: {
        placeholder: "请输入",
        modules: {
          toolbar: [
            ["bold", "italic", "underline", "strike"], //加粗，斜体，下划线，删除线
            ["blockquote", "code-block"], //引用，代码块
            [{ header: 1 }, { header: 2 }], // 标题，键值对的形式；1、2表示字体大小

            [{ size: ["small", false, "large", "huge"] }], // 字体大小
            [{ header: [1, 2, 3, 4, 5, 6, false] }], //几级标题
            [{ color: [] }, { background: [] }], // 字体颜色，字体背景颜色
            [{ align: [] }], //对齐方式
            ["clean"] //清除字体样式
          ]
        }
      }
    };
  },
  methods: {
    handleDeleteBatchTips() {
      let applyIdListStr = this.applyIdList.join();
      if (!applyIdListStr) {
        return this.$message.warning("至少选中一条数据");
      }

      this.deleteBatchDialog = true;
    },
    batchDelete() {
      let applyIdListStr = this.applyIdList.join();
      this.$http
        .delete("/apply/ids", {
          params: {
            applyIdList: applyIdListStr
          }
        })
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            this.reload();
            return this.$message.success(msg);
          } else if (code == 400) {
            return this.$message.info(msg);
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    onSubmitApply(applyRef) {
      this.$refs[applyRef].validate(valid => {
        if (valid) {
          // applicant
          this.$http
            .put("/apply/data/all/", this.applyData)
            .then(resp => {
              let { code, msg, data } = resp.data;
              if (code == 1) {
                this.dialogFormVisible = false;
                this.reload();
                return this.$message.info(msg);
              }
              return this.$message.error(msg);
            })
            .catch(resp => {});
        } else {
          this.$message.warning("信息不完整呀");
          return false;
        }
      });
    },
    checkIsConflict() {
      this.queryReviewHistory();
      this.queryCourseHistory();
    },
    queryReviewHistory() {
      let name = this.$route.query.name;
      this.$http
        .get("/apply/history", {
          params: {
            beginTime: this.applyData.beginTime,
            endTime: this.applyData.endTime,
            name: this.applyData.classroomName
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 404) {
            // 不存在记录，可以使用
            this.isDisableSubmitButton = false;
            return;
          } else if (code == 400) {
            // 开始时间大于结束时间，不可使用
            this.$message.info(msg);
            this.isDisableSubmitButton = true;
            return;
          } else if (code == 1) {
            // 存在记录，不可用使用
            let { total } = resp.data.data.pageResult;
            this.$message.warning(
              "当前时间段与 " +
                total +
                " 条 预定信息 安排冲突了，请选择合适时间段哦"
            );
            this.isDisableSubmitButton = true;
            return;
          }
          // 其他情况(code=0)
          this.$message.warning("服务器出错" + msg);
          this.isDisableSubmitButton = true;
        })
        .catch(resp => {});
    },
    queryCourseHistory() {
      let name = this.$route.query.name;
      this.$http
        .get("course/history", {
          params: {
            beginTime: this.applyData.beginTime,
            endTime: this.applyData.endTime,
            name: this.applyData.classroomName
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 1) {
            let { total } = resp.data.data.pageResult;
            this.$message.warning(
              "当前时间段与 " + total + "条 课程安排 冲突了，请选择合适时间段哦"
            );
            this.isDisableSubmitButton = true;
            return;
          } else if (code == 400) {
            this.$message.info(msg);
            this.isDisableSubmitButton = true;
            return;
          } else if (code == 404) {
            this.isDisableSubmitButton = false;
            return;
          }
          this.$message.warning("服务器出错" + msg);
          this.isDisableSubmitButton = true;
        })
        .catch(resp => {});
    },

    changeClassroom() {
      this.$http
        .get("/classroom/noAuthorize/getClassroomOptions/")
        .then(resp => {
          let { code, msg, data } = resp.data;
          if (code == 1) {
            this.classroomOptions = data.options;
          }
        })
        .catch(resp => {});
    },
    // 过滤状态
    filterTag(value, row) {
      return row.applyStatus === value;
    },
    handleSelectionChange(applyList) {
      let applyIdList = [];
      applyList.forEach(e => {
        applyIdList.push(e.applyId);
      });

      this.applyIdList = applyIdList;
    },
    handleEdit(index, row) {
      this.dialogFormVisible = true;
      this.applyData = row;
    },
    handleDelete(index, row) {
      this.$http
        .delete(`apply/apply-id/${row.applyId}`)
        .then(resp => {
          let { code, msg } = resp.data;
          if (code == 1) {
            this.getCurrentLoginUserApplyHistory();
            this.isShowDeleteDialog = false;
            this.reload();
            return this.$message.success("删除成功");
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },
    handleSizeChange(size) {
      this.$http
        .get("/apply/list/apply/userId", {
          params: {
            page: this.currentPage,
            limit: size,
            key: this.key
          }
        })
        .then(resp => {
          let { data, code, msg } = resp.data;
          if (code == 1) {
            this.total = parseInt(data.mapResultData.total);
            this.applyDataList = data.mapResultData.applyReportVOList;
            return;
          } else {
            this.$message.info("当前没有预定信息");
          }
        })
        .catch(resp => {});
    },
    handleCurrentChange(page) {
      this.$http
        .get("/apply/list/apply/userId", {
          params: {
            page: page,
            limit: this.size,
            key: this.key
          }
        })
        .then(resp => {
          let { data, code, msg } = resp.data;
          if (code == 1) {
            this.total = parseInt(data.mapResultData.total);
            this.applyDataList = data.mapResultData.applyReportVOList;

            return;
          } else {
            this.$message.info("当前没有预定信息");
          }
        })
        .catch(resp => {});
    },
    getCurrentLoginUserApplyHistory() {
      this.$http
        .get("apply/list/apply/userId", {
          params: {
            page: this.currentPage,
            limit: this.size,
            key: this.key
          }
        })
        .then(resp => {
          let { data, code, msg } = resp.data;
          if (code == 1) {
            console.log(resp);
            this.isShowTable = true;
            this.total = parseInt(data.mapResultData.total);
            this.applyDataList = data.mapResultData.applyReportVOList;
            return;
          }
          this.$message.warning("当前没有申请教室信息");
        })
        .catch(resp => {});
    },
    search() {
      this.$http
        .get("apply/list/apply/userId", {
          params: {
            page: this.currentPage,
            limit: this.size,
            key: this.key
          }
        })
        .then(resp => {
          let { data, code, msg } = resp.data;
          if (code == 1) {
            let total = parseInt(data.mapResultData.total);
            this.total = total;
            this.applyDataList = data.mapResultData.applyReportVOList;
            this.$message.warning(`一共 ${total} 条记录`);
            return;
          } else {
            this.$message.info("当前没有预定信息");
          }
        })
        .catch(resp => {});
    }
  },
  created() {
    this.getCurrentLoginUserApplyHistory();
  }
};
</script>

<style scoped lang='less'>
.el-card {
  margin-top: 10px;
}
.el-pagination {
  margin-top: 20px;
}
.search {
  margin-top: 10px;
}
.el-input {
  width: 200px;
}
.el-form-item {
  width: 300px;
  .el-textarea {
    width: 528px;
  }
}
.el-card {
  border-radius: 30px;
}
.edit_container {
  width: 530px;
}
</style>